package com.example.managerment.aop;



import com.example.managerment.module.dto.UsersDTO;
import com.example.managerment.module.vo.ResultVO;
import com.example.managerment.util.JwtUtil;
import com.example.managerment.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        登录成功将验证码清空
        request.getSession().setAttribute("VERIFY_CODE", "");

        //获取当前用户
        UsersDTO master = (UsersDTO) authentication.getPrincipal();

        //将用户身份写到上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //将用户身份保存到redis
        redisUtil.save(String.valueOf(master.getUserId()),authentication);

        //生成token
        String token = jwtUtil.generateToken(String.valueOf(master.getUserId()));

        //保存token到redis中
        redisUtil.save(String.valueOf(master.getUserId()), token);

        //写响应头
        response.setHeader("token",token);
//        System.out.println(master);
        //成功响应

        master.setAccessToken(token);
        ResultVO resultVO = new ResultVO(master);
        resultVO.out(response);
    }
}
